package com.aliware.tianchi.netty;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.RpcContext;

import com.aliware.tianchi.HashInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static com.aliware.tianchi.Constants.nacosAddress;

public class InitProviderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpProcessHandler.class);
    private HashInterface stub = createNewRefConf();

    void doInit() {
        for (int i = 0; i < 100; i++) {
            CompletableFuture<Integer> hey = stub.hash("hey");
            hey.whenComplete((a, t) -> {
                if (t == null) {
                    LOGGER.info("Init hash service successful. address:{} result:{}", RpcContext.getContext().getRemoteHost(), a, t);
                } else {
                    LOGGER.error("Init hash service failed. address:{} ", RpcContext.getContext().getRemoteHost(), t);
                }
            });
        }
    }

    private HashInterface createNewRefConf() {
        ApplicationConfig application = new ApplicationConfig();
        application.setName("service-gateway");

        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(nacosAddress());

        ReferenceConfig<HashInterface> reference = new ReferenceConfig<>();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setInterface(HashInterface.class);

        Map<String, String> attributes = new HashMap<>();
        attributes.put("loadbalance", "user");
        attributes.put("cluster", "user");
        attributes.put(Constants.HEARTBEAT_KEY, "0");
        attributes.put(Constants.RECONNECT_KEY, "false");
        reference.setParameters(attributes);

        return reference.get();
    }

}
